package com.example.todosample2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.style.BulletSpan;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

public class MainActivity extends Activity {

	private static final int INSERT_CONSTANT = 1;
	private static final int MODIFY_CONSTANT = 2;
	private static final int DELETE_CONSTANT = 3;
	// Database Helper
	DatabaseHelper db;
	final ArrayList<Todo> arrayList = new ArrayList<Todo>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		db = new DatabaseHelper(getApplicationContext());

		List<Todo> allToDos = db.getAllToDos();
		for (Todo todo : allToDos) {
			arrayList.add(todo);
		}

		Button insertButton = (Button) this.findViewById(R.id.insertButton);
		Button sendButton = (Button) this.findViewById(R.id.sendButton);
		Button allDeleteButton = (Button) this
				.findViewById(R.id.allDeleteButton);

		ListView listView = (ListView) this.findViewById(R.id.listView);
		final EditText insertTodo = (EditText) this.findViewById(R.id.editTodo);

		final TodoListAdapter arrayAdapter = new TodoListAdapter(this,
				R.layout.row, arrayList);
		listView.setAdapter(arrayAdapter);
		registerForContextMenu(listView);

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("내용 전체 삭제");
		builder.setMessage("모두 삭제하시겠습니까?");
		builder.setIcon(android.R.drawable.ic_dialog_alert);

		android.content.DialogInterface.OnClickListener poslistener = new android.content.DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				db.deleteToDoAll();
				arrayList.clear();
				arrayAdapter.notifyDataSetChanged();
			}
		};
		android.content.DialogInterface.OnClickListener neglistener = new android.content.DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				return;
			}

		};

		builder.setPositiveButton("예", poslistener);
		builder.setNegativeButton("아니오", neglistener);
/*************************************************************************************************/
		insertButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String todo;
				todo = insertTodo.getText().toString();
				if (todo == "")
					return;

				Todo new_todo = new Todo(todo);

				long id = db.createToDo(new_todo);
				SendServer sendserver = new SendServer(INSERT_CONSTANT,
						(int) id, todo);
				long send_id = db.createSendserver(sendserver);

				new_todo.setId((int) id);

				arrayList.add(new_todo);

				arrayAdapter.notifyDataSetChanged();
				insertTodo.setText("");
			}
		});
		
		allDeleteButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				builder.show();
			}
		});
		
		sendButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				List<SendServer> sendList = db.getAllSends();
				if (sendList.isEmpty())
					return;
				String json = new Gson().toJson(sendList);
				// String url =
				// "http://192.168.0.194:8080/testServer/JSONServer.jsp";
				String url = "http://192.168.0.197:8080/myapp/SyncTodo.do";

				ArrayList<String> param = new ArrayList<String>();

				param.add("url=" + url);

				// String parm = "msg=";
				String parm = "data=";
				parm += json;

				HttpResponse result = null;

				try {

					result = new Network().execute(url, parm).get();
					db.deleteSendsAll();
					processEntity(result);

				} catch (InterruptedException e) {

					e.printStackTrace();

				} catch (ExecutionException e) {

					e.printStackTrace();

				}

			}
		});
		db.closeDB();

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.listView) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			menu.setHeaderTitle(arrayList.get(info.position).getNote());
			menu.add(Menu.NONE, 0, 0, "수정");
			menu.add(Menu.NONE, 1, 1, "삭제");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		String[] menuItems = { "수정", "삭제" };
		String menuItemName = menuItems[menuItemIndex];
		String listItemName = arrayList.get(info.position).getNote();

		Toast t = Toast.makeText(this, String.format("Selected %s for item %s",
				menuItemName, listItemName), Toast.LENGTH_LONG);
		t.show();
		return true;

	}

	private void processEntity(HttpResponse rtnResult)

	{
		HttpEntity entity = rtnResult.getEntity();
		BufferedReader br;
		String line, result = "";

		try
		{
			br = new BufferedReader(new InputStreamReader(entity.getContent(),
					"UTF-8"));
			while ((line = br.readLine()) != null)
			{
				result += line;
			}
			Log.i("send server", "결과 == " + result);

		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();

		} catch (IllegalStateException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}